package cn.wolfcode.web.controller;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.service.IEmployeeService;
import cn.wolfcode.util.JsonResult;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

@Controller
public class LoginController {
    @Autowired
    private IEmployeeService employeeService;

    @RequestMapping("/login")
    @ResponseBody
    public JsonResult login (String username, String password, HttpSession session) {
        try {
            //通过login页面异步请求获取到的用户名和密码封装令牌
            UsernamePasswordToken token = new UsernamePasswordToken(username, password);
            //获取登录的用户名
            Object name = token.getPrincipal();
            Employee employee = employeeService.selectByName((String) name);
            //判断账号是否为禁用状态,true为非正常状态,如果是true,取反然后抛出异常
            if (!employee.isStatus()) {
                //指定抛出的账号禁用异常
                throw new DisabledAccountException();
            }
            //利用shirp的api来登录
            SecurityUtils.getSubject().login(token);
            return new JsonResult();
        } catch (UnknownAccountException e) {
            return new JsonResult(false, "账号不存在");
        } catch (IncorrectCredentialsException e) {
            return new JsonResult(false, "密码错误");
        } catch (DisabledAccountException e) {
            //账号禁用异常
            return new JsonResult(false, "账号被禁用,不能登录");
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResult(false, "登录异常，请联系管理员");
        }
    }


}
